package com.jz.netthings.netty.server;


import com.jz.netthings.netty.protocol.BasePacket;
import com.jz.netthings.netty.protocol.bean.ZxdcLoginPacket;
import com.jz.netthings.netty.protocol.bean.ZxdcMsgPacket;
import com.jz.netthings.netty.support.ServerHandlerSupport;
import com.jz.netthings.netty.utils.NettyMsgHelper;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("nettyChairServerHandler")
@ChannelHandler.Sharable
public class NettyChairServerHandler extends SimpleChannelInboundHandler {

    Logger logger = LoggerFactory.getLogger(getClass());


    @Autowired
    ServerHandlerSupport nettyServerHandlerSupport;

    public NettyChairServerHandler() {
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object obj) throws Exception {
//        System.out.println("NettyChairServerHandler channelRead0..."+obj);
        if (obj instanceof ZxdcLoginPacket) {

            NettyMsgHelper.handlerZxdcLogin((ZxdcLoginPacket) obj, nettyServerHandlerSupport, ctx);

            NettyMsgHelper.sendTimeStampMsgToChair(ctx);

        } else if (obj instanceof byte[]) {
            byte[] msgByte = (byte[]) obj;
            ZxdcMsgPacket packet = NettyMsgHelper.bytesToPacket(msgByte);

            if(!"online".equals(packet.getCmd())){
                logger.info("平板【" + ctx.channel().remoteAddress() + "】消息：" + packet);
            }

            packet.setCtx(ctx);
            ZxdcMsgPacket targetPacket = nettyServerHandlerSupport.handleChairPacket(packet);
            if (targetPacket != null) {
                NettyMsgHelper.sendPacketToChair(ctx, targetPacket);
            }

        }
    }
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (IdleState.READER_IDLE.equals(event.state())) {
//                logger.info("服务器给平板【" + ctx.channel().remoteAddress() + "】发送心跳信息...");
                NettyMsgHelper.sendOnlineMsgToChair(ctx);
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("【" + this + "】连接的客户端【nettyZxdcServerHandler】地址:" + ctx.channel().remoteAddress());
        super.channelActive(ctx);
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {

        super.channelRead(ctx,obj);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //捕捉异常信息
        logger.error(cause.getMessage() + "【" + ctx.channel().remoteAddress() + "】");
        //出现异常时关闭channel
        ctx.channel().close();
        ctx.close();
        super.exceptionCaught(ctx,cause);
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        System.out.println("-----------------------------------------");

        super.channelInactive(ctx);
    }
}